<template>
  <div class="detail-container">
    <h1>欢迎{{ user }}小可爱！</h1>
    <br>
    <p v-if="errorMsg" style="color:red;">{{ errorMsg }}</p>
    <div v-if="infos.length === 0">
      咋妹有数据捏？
    </div>
    <ul v-else>
      <li v-for="(info, index) in infos" :key="index">
        <span class="name">{{ info.name }}</span>
        <span class="id-num">{{ info.idNum }}</span>
      </li>
    </ul>
    <button class="refresh-btn" @click="refreshData">刷新</button>
    <br>
    <button class="logout-btn" @click="logOut">登出</button>
  </div>
</template>
  
<script>
export default {
  data() {
    return {
      user: '',
      infos: [],
      errorMsg: '',
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      const token = localStorage.getItem('token')
      fetch('/api/detail', {
        headers: {
          'Authorization': `${token}`,
        },
      })
        .then(response => response.json())
        .then(data => {
          if (data.code === 0) {
            this.user = data.data.user
            this.infos = data.data.infos
            this.errorMsg = ''
          } else if (data.code === -99) {
            localStorage.removeItem('token')
            this.$router.push('/login')
          } else {
            this.errorMsg = data.msg
          }
        })
        .catch(error => {
          console.error('Error:', error)
          this.errorMsg = '请求出错，请稍后再试！'
        })
    },
    refreshData() {
      this.fetchData();
    },
    logOut() {
      localStorage.removeItem('token')
      this.$router.push('/login')
    }
  },
};
</script>
  
<style scoped>
.detail-container {
  max-width: 500px;
  margin: 0 auto;
  padding: 30px;
  text-align: center;
}

h1 {
  font-size: 32px;
  margin-bottom: 20px;
}

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

li {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f5f5f5;
}

.name {
  flex-grow: 1;
  text-align: left;
  font-size: 16px;
}

.id-num {
  flex-shrink: 0;
  font-size: 14px;
  color: #999;
}

.refresh-btn {
  display: block;
  margin: 20px auto 0;
  padding: 10px 20px;
  background-color: #4caf50;
  color: #fff;
  border-radius: 4px;
  font-size: 18px;
  cursor: pointer;
}

.logout-btn {
  display: block;
  margin: 10px auto 0;
  padding: 5px 10px;
  background-color: #125b55;
  color: #ece7e7;
  border-radius: 4px;
  font-size: 15px;
  cursor: pointer;
}
</style>
  